﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using winForm = System.Windows.Forms;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using SpreadsheetGear;
using SpreadsheetGear.Windows.Controls;
using WPFWorkbookDesigner;
using WPFWorkbookDesigner.Addons;
using WPFWorkbookDesigner.Events;
using WPFWorkbookDesigner.UI;

namespace WPFWorkbookDesigner.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        [PreferredConstructor]
        public MainViewModel()
        {
            Messenger.Default.Register<OpenWorkbookEvent>(this, OpenWorkbook);
            Messenger.Default.Register<FindOutTargetWindowEvent>(this, Respond);

            OpenWorkbookCommand = new RelayCommand(OpenWorkbook, GetIsNotEditingStatus);
            AddNewWorkbookCommand = new RelayCommand(AddNewWorkbook, GetIsNotEditingStatus);
            SaveWorkbookCommand = new RelayCommand(Save, GetIsNotEditingStatus);
            SaveAsCommand = new RelayCommand(SaveAs, GetIsNotEditingStatus);

            WindowLoadedCommand = new RelayCommand<RoutedEventArgs>(WindowLoadedHandler);
            WindowClosingCommand = new RelayCommand<CancelEventArgs>(WindowClosingHandler);
            WindowClosedCommand = new RelayCommand<EventArgs>(WindowClosedHandler);
            WindowActivatedCommand = new RelayCommand(WindowActivatedHandler);

        }
        public Window Interface { private get; set; }

        public WorkbookView View { private get; set; }

        public string WindowTitle
        {
            get { return _windowTitle; }
            private set
            {
                _windowTitle = value;
                RaisePropertyChanged();
            }
        }

        public override void Cleanup()
        {
            Messenger.Default.Unregister<FindOutTargetWindowEvent>(this, Respond);


            View.CellBeginEdit -= ViewOnCellBeginEdit;
            View.CellCancelEdit -= View_CellCancelEdit;
            View.CellEndEdit -= ViewOnCellEndEdit;

            View = null;
            Interface = null;
            base.Cleanup();
        }

        #region field

        private static readonly WindowManager WinManager = WindowManager.GetInstance();
        private string _windowTitle;

        #endregion
        #region Command


        public RelayCommand AddNewWorkbookCommand { get; private set; }
        public RelayCommand OpenWorkbookCommand { get; private set; }
        public RelayCommand SaveAsCommand { get; private set; }
        public RelayCommand SaveWorkbookCommand { get; private set; }


        public RelayCommand<EventArgs> WindowClosedCommand { get; private set; }
        public RelayCommand<CancelEventArgs> WindowClosingCommand { get; private set; }
        public RelayCommand<RoutedEventArgs> WindowLoadedCommand { get; private set; }
        public RelayCommand WindowActivatedCommand { get; private set; }

        #endregion

        #region Methods

        private static void AddNewWorkbook()
        {
            var book = WinManager.BookSet.Dowork(s => s.Workbooks.Add());
            WinManager.CreateWindow(book);
        }

        private static winForm.OpenFileDialog GetOpenFileDialog()
        {
            winForm.OpenFileDialog dia = new winForm.OpenFileDialog()
            {
                Multiselect = true,
                Filter = Properties.Resources.FileDialogFormatFilter,
                FilterIndex = 1,
                AddExtension = true,

            };
            return dia;
        }

        private static winForm.SaveFileDialog GetSaveFileDialog(string fileName, string title = "保存")
        {
            var dia = new winForm.SaveFileDialog
            {
                FilterIndex = 2,
                OverwritePrompt = true,
                FileName = fileName,
                Title = title,
                CheckPathExists = true,
                ValidateNames = true,
                AutoUpgradeEnabled = true,
                Filter = Properties.Resources.FileDialogFormatFilter,
            };
            return dia;
        }

        private static void OpenWorkbook()
        {
            var dia = GetOpenFileDialog();
            if (dia.ShowDialog() != winForm.DialogResult.OK)
                return;
            var set = WinManager.BookSet;
            foreach (var path in dia.FileNames)
            {
                var book = set.Dowork(s => s.Workbooks.Open(path));
                WinManager.CreateWindow(book);
            }
        }

        private void Respond(FindOutTargetWindowEvent e)
        {
            if (!e.Workbook.Equals(View.ActiveWorkbook))
                return;
            Interface.Show();
            Interface.Activate();
        }

        private bool GetIsNotEditingStatus()
        {
            return !View?.IsEditing ?? false;
        }

        private bool GetIsNotEditingStatus<T>(T para) where T : class
        {
            return !View?.IsEditing ?? false;
        }

        private void OpenWorkbook(OpenWorkbookEvent e)
        {
            View.Dowork(v =>
            {
                v.ActiveWorkbook = e.Workbook;
                WindowTitle = $"{e.Workbook.Name} - {Properties.Resources.Title}";
            });
            Messenger.Default.Unregister<OpenWorkbookEvent>(this, OpenWorkbook);
        }
        /// <summary>
        /// 保存工作簿
        /// </summary>
        /// <returns></returns>
        private void Save()
        {
            var book = View.ActiveWorkbook;
            if (!book.IsModified)
                return;
            if (IsUnsavedBook(book))
                SaveAs();//ps 可能需要改进文件保存逻辑
            else
            {
                View.Dowork(x => book.Save());
            }
        }

        private void SaveAs()
        {
            View.Dowork(v =>
            {
                var book = v.ActiveWorkbook;
                using (var dia = GetSaveFileDialog(book.Name))
                {
                    if (dia.ShowDialog() == winForm.DialogResult.OK)
                    {
                        book.SaveAs(dia.FileName, FileFormat.OpenXMLWorkbook);
                    }
                }
            });
        }

        private static bool IsUnsavedBook(IWorkbook book)
        {
            return book.FullName == book.Name && book.Name.StartsWith("Book");
        }
        #endregion

        #region event handler

        

        private void View_CellCancelEdit(object sender, CellCancelEditEventArgs e)
        {

        }

        private void ViewOnCellBeginEdit(object sender, CellBeginEditEventArgs e)
        {

        }

        private void ViewOnCellEndEdit(object sender, CellEndEditEventArgs cellEndEditEventArgs)
        {

        }

        private void WindowClosedHandler(EventArgs e)
        {
            Cleanup();
        }

        private void WindowClosingHandler(CancelEventArgs e)
        {
            var book = View.ActiveWorkbook;
            if (!book.IsModified)
                return;

            switch (MesBox.Warning($"退出程序前是否保存工作簿?", MessageBoxButton.YesNoCancel))
            {
                case MessageBoxResult.Yes:
                    Save();
                    if (book.IsModified)
                        e.Cancel = true;
                    break;
                case MessageBoxResult.No:
                    e.Cancel = false;
                    break;
                case MessageBoxResult.Cancel:
                    e.Cancel = true;
                    return;
            }
            View.Dowork(v => v.ActiveWorkbook.Close());
        }

        private void WindowLoadedHandler(RoutedEventArgs e)
        {
            View.CellBeginEdit += ViewOnCellBeginEdit;
            View.CellCancelEdit += View_CellCancelEdit;
            View.CellEndEdit += ViewOnCellEndEdit;
        }

        private void WindowActivatedHandler()
        {
            ((App) Application.Current).MainWindow = Interface;
            //Messenger.Default.Send(new BroadcastActiveViewEvent(View));
        }

        #endregion

    }
}